import React, { useState, useEffect } from 'react';
import { Table, Button, message, Input, Modal } from 'antd';
import { useNavigate } from 'react-router-dom';
import { SearchOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import {request} from "../utils/requset";

const { confirm } = Modal;
const PzscTable = ({ mode }) => {
  const navigate = useNavigate();
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 存储选中的行
  const [selectedRows, setSelectedRows] = useState([]); // 选中的数据行
  const [searchText, setSearchText] = useState(''); // 存储搜索文本
  const [searchedColumn, setSearchedColumn] = useState(''); // 存储搜索的列
  const [runLoading, setRunLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await request.get(`/rpa/${mode}/tj`);
        // if (!response.ok) throw new Error('数据请求失败');
        const rows = response.data.rows || [];

        setData(rows);

        if (rows.length > 0) {
          const excludeColumns = ['id']; // 需要排除的列
          const dynamicColumns = Object.keys(rows[0])
            .filter(key => !excludeColumns.includes(key))
            .map(key => ({
              title: key,
              dataIndex: key,
              key: key,
              render: text => (
                key === '账簿编号' ? (
                  <span style={{ color: text !== '01051507' ? 'red' : 'inherit' }}>
                    {text}
                  </span>
                ) : text
              ),
              filters: [
                ...new Set(rows.map(row => row[key])).values(),
              ].map(value => ({ text: value, value })),
              onFilter: (value, record) => record[key].toString().toLowerCase().includes(value.toLowerCase()),
              filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
              filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div style={{ padding: 8 }}>
                  <Input
                    placeholder={`搜索 ${key}`}
                    value={selectedKeys[0]}
                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys, confirm, key)}
                    style={{ marginBottom: 8, display: 'block' }}
                  />
                  <Button
                    type="primary"
                    onClick={() => handleSearch(selectedKeys, confirm, key)}
                    icon={<SearchOutlined />}
                    size="small"
                    style={{ width: 90, marginRight: 8 }}
                  >
                    搜索
                  </Button>
                  <Button onClick={() => handleReset(clearFilters, confirm)} size="small" style={{ width: 90 }}>
                    重置
                  </Button>
                </div>
              ),
            }));

          setColumns(dynamicColumns);
        }
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };

    fetchData();
  }, [mode]); // mode 变化时重新获取数据

  // 删除所有
  const handleDeleteAll = () => {
    confirm({
      title: '确定要删除所有项吗？',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将无法恢复，请谨慎操作。',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      style: { top: "30%" },
      transitionName: 'ant-fade',
      onOk() {
        performDeleteAll();
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const performDeleteAll = async () => {
    try {
      setRunLoading(true);
      const response = await request.post(`/rpa/${mode}/deleteall`, {
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ rows: '' }),
      });

      // if (!response.ok) throw new Error('删除失败');

      message.success('删除成功！');
      setData([]);
    } catch (error) {
      console.error('删除请求失败:', error);
      message.error('删除失败，请稍后重试');
    } finally {
      setRunLoading(false);
    }
  };

  // 删除选中
  const handleDelete = () => {
    confirm({
      title: '确定要删除选中的项吗？',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将无法恢复，请谨慎操作。',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      style: { top: "30%" },
      transitionName: 'ant-fade',
      onOk() {
        performDelete();
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const performDelete = async () => {
    if (selectedRows.length === 0) {
      message.warning('请先选择要删除的项！');
      return;
    }
    setRunLoading(true);

    try {
      const response = await request.post(`/rpa/${mode}/delete`, {
        rows: selectedRows
      });

      // if (!response.ok) throw new Error('删除失败');

      message.success('删除成功！');
      // 过滤掉已删除的行，更新表格数据
      setData(prevData => prevData.filter(row => !selectedRowKeys.includes(row.id)));
      setSelectedRowKeys([]); // 清空选中状态
      setSelectedRows([]);
    } catch (error) {
      console.error('删除请求失败:', error);
      message.error('删除失败，请稍后重试');
    } finally {
      setRunLoading(false);
    }
  };

  // 处理勾选
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys, rows) => {
      setSelectedRowKeys(keys);
      setSelectedRows(rows);
    },
  };

  // 添加行点击事件
  const onRow = (record) => {
    return {
      onClick: () => {
        const rowIndex = data.findIndex(row => row.id === record.id);
        if (rowIndex > -1) {
          const newSelectedRowKeys = [...selectedRowKeys];
          const newSelectedRows = [...selectedRows];

          if (newSelectedRowKeys.includes(record.id)) {
            const index = newSelectedRowKeys.indexOf(record.id);
            newSelectedRowKeys.splice(index, 1);
            newSelectedRows.splice(index, 1);
          } else {
            newSelectedRowKeys.push(record.id);
            newSelectedRows.push(record);
          }

          setSelectedRowKeys(newSelectedRowKeys);
          setSelectedRows(newSelectedRows);
        }
      },
    };
  };

  // 处理搜索
  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  // 处理重置
  const handleReset = (clearFilters, confirm) => {
    clearFilters();
    setSearchText('');
    setSearchedColumn('');
    confirm();
  };

  // 自定义过滤函数
  const customFilter = (record) => {
    if (!searchText || !searchedColumn) {
      return true;
    }
    return record[searchedColumn].toString().toLowerCase().includes(searchText.toLowerCase());
  };

  return (
    <div>
      <Button
        type="primary"
        onClick={handleDelete}
        loading={runLoading}
        disabled={selectedRows.length === 0}
        style={{ marginBottom: 16, marginLeft: 16, float: 'right' }}
      >
        删除选中项
      </Button>
      <Button
        type="primary"
        onClick={handleDeleteAll}
        loading={runLoading}
        style={{ marginBottom: 16, marginLeft: 16, float: 'right' }}
      >
        删除全部
      </Button>
      <Button
        onClick={() => navigate('/robot/rpa/nw'+mode.slice(0,-2))}
        style={{ marginBottom: 16, marginLeft: 16, float: 'right' }}
      >
        明细查询
      </Button>
      <Table
        rowSelection={rowSelection} // 添加勾选功能
        dataSource={data.filter(customFilter)}
        columns={columns}
        rowKey="id"
        showSizeChanger
        onRow={onRow}
        scroll={{x: 'max-content', y: `max(calc(100vh - 614.135px), 200px)`}} // 启用水平和垂直滚动
        pagination={false}
      />
    </div>
  );
};

export default PzscTable;
